Do you want to keep hackers out of your checking account?
Yes.
private
Visibility Modifier
When an instance variable is declared private
it can
be used only by the methods of that class.
Here is the checking account class definition from the last
chapter with each of its variables declared to be private
.
Now only the methods of a CheckingAccount
object
can "see" accountNumber
, accountHolder,
and balance.
There is no change in these methods because their access to the instance
variables is the same as before.
class CheckingAccount { // variable declarations private String accountNumber; private String accountHolder; private int balance; //constructor CheckingAccount( String accNumber, String holder, int start ) { accountNumber = accNumber ; accountHolder = holder ; balance = start ; } // methods int getBalance() { return balance ; } void processDeposit( int amount ) { balance = balance + amount ; } void processCheck( int amount ) { int charge; if ( balance < 100000 ) charge = 15; else charge = 0; balance = balance - amount - charge ; } }
The balance
can no longer be changed outside of the object with an assignment statement.
How can you change the balance in a CheckingAccount
object?